package com.carbon.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carbon.common.core.domain.AjaxResult;
import com.carbon.common.utils.SecurityUtils;
import com.carbon.common.utils.StringUtils;
import com.carbon.common.utils.bean.BeanUtils;
import com.carbon.domain.Ware;
import com.carbon.dto.WareDto;
import com.carbon.dto.WareNodeTree;
import com.carbon.service.WareService;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import com.carbon.vo.SearchParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 仓库(Ware)表控制层
 *
 * @author WangFK
 * @since 2023-08-21 13:19:47
 */
@RestController
@Slf4j
@RequestMapping("/wms/ware")
public class WareController {
    /**
     * 服务对象
     */
    @Resource
    private WareService wareService;

    /**
     * 查询仓库树形结构
     */
    @GetMapping("/getCascaderWare")
    public AjaxResult getCascaderWare() {
        LambdaUpdateWrapper<Ware> lqw = new LambdaUpdateWrapper<Ware>()
                .eq(Ware::getStatus, "0")
                .orderByAsc(Ware::getSort)
                .orderByAsc(Ware::getCreateTime);
        List<Ware> list = wareService.list(lqw);
        List<WareNodeTree> treeList = BeanUtil.copyToList(list, WareNodeTree.class);
        if (ObjectUtil.isNotEmpty(list)) {
            treeList = wareService.getWareTreeNode(treeList);

            return AjaxResult.success(treeList);
        }
        return AjaxResult.success();
    }

    @GetMapping("/list")
    public AjaxResult list(SearchParams params) {
        Page<Ware> warePage = new Page<>(params.getPageNum(), params.getPageNum());
        LambdaUpdateWrapper<Ware> lqw = new LambdaUpdateWrapper<Ware>()
                .orderByAsc(Ware::getSort)
                .orderByAsc(Ware::getCreateTime);
        String wareId = params.getWareId();
        String level = params.getLevel();
        lqw.like(ObjectUtil.isNotEmpty(params.getSearch()), Ware::getWareName, params.getSearch());
        if (ObjectUtil.isNotEmpty(wareId)) {
            lqw.eq(Ware::getParendId, wareId);
        } else {
            lqw.eq(Ware::getParendId, "0");
        }
        warePage = wareService.page(warePage, lqw);
        List<Ware> records = warePage.getRecords();
        if (ObjectUtil.isEmpty(records)) {
            return AjaxResult.success();
        }
        ArrayList<WareDto> wareDtos = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(level)) {
            if ("1".equals(level)) {
                Ware byId = wareService.getById(wareId);
                records.stream().forEach(item -> {
                    WareDto wareDto = new WareDto();
                    BeanUtil.copyProperties(item,wareDto);
                    // 仓库
                    wareDto.setWareNameDto(byId.getWareName());
                    // 库区
                    wareDto.setWareAreaDto(item.getWareName());
                    wareDtos.add(wareDto);
                });
            }
            if ("2".equals(level)) {
                Ware byId = wareService.getById(wareId);
                Ware byId1 = wareService.getById(byId.getParendId());
                records.stream().forEach(item -> {
                    WareDto wareDto = new WareDto();
                    BeanUtil.copyProperties(item,wareDto);
                    // 仓库
                    wareDto.setWareNameDto(byId1.getWareName());
                    // 库区
                    wareDto.setWareAreaDto(byId.getWareName());
                    // 库位
                    wareDto.setWarePositionDto(item.getWareName());
                    wareDtos.add(wareDto);
                });
            }
            return AjaxResult.success()
                    .put("total", warePage.getTotal())
                    .put("rows", wareDtos);
        }

        records.stream().forEach(item -> {
            WareDto wareDto = new WareDto();
            BeanUtil.copyProperties(item,wareDto);
            // 仓库
            wareDto.setWareNameDto(item.getWareName());
            wareDtos.add(wareDto);
        });
        return AjaxResult.success()
                .put("total", warePage.getTotal())
                .put("rows", wareDtos);

    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public AjaxResult selectOne(@PathVariable Serializable id) {
        Ware byId = wareService.getById(id);
        return AjaxResult.success(byId);
    }

    /**
     * 新增数据
     *
     * @param ware 实体对象
     * @return 新增结果
     */
    @PostMapping
    public AjaxResult insert(@RequestBody Ware ware) {
        if (ObjectUtil.isEmpty(ware.getWareName())) {
            return AjaxResult.error("仓库名为空");
        }
        if (ObjectUtil.isEmpty(ware.getLevel())) {
            return AjaxResult.error("层级为空");
        }
        if (ware.getLevel().compareTo("3") > 0) {
            return AjaxResult.error("层级错误");
        }
        if (ObjectUtil.isNotEmpty(ware.getId())) {
            return update(ware);
        }
        LambdaUpdateWrapper<Ware> lqw = new LambdaUpdateWrapper<Ware>()
                .eq(Ware::getWareName, ware.getWareName())
                .eq(Ware::getStatus, "0");
        List<Ware> list = wareService.list(lqw);
        if (ObjectUtil.isNotEmpty(list)) {
            return AjaxResult.error("仓库名:" + ware.getWareName() + "重复");
        }
        ware.setCreateBy(SecurityUtils.getUsername());
        ware.setCreateTime(DateUtil.date());
        return wareService.save(ware) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 修改数据
     *
     * @param ware 实体对象
     * @return 修改结果
     */
    @PutMapping
    public AjaxResult update(@RequestBody Ware ware) {
        Ware byId = wareService.getById(ware.getId());
        if (!byId.getWareName().equals(ware.getWareName())) {
            LambdaUpdateWrapper<Ware> lqw = new LambdaUpdateWrapper<Ware>()
                    .eq(Ware::getWareName, ware.getWareName())
                    .eq(Ware::getStatus, "0");
            List<Ware> list = wareService.list(lqw);
            if (ObjectUtil.isNotEmpty(list)) {
                return AjaxResult.error("仓库名:" + ware.getWareName() + "重复");
            }
        }
        ware.setUpdateBy(SecurityUtils.getUsername());
        ware.setUpdateTime(DateUtil.date());
        return wareService.updateById(ware) ? AjaxResult.success() : AjaxResult.error();
    }

    /**
     * 删除数据
     *
     * @param id 主键结合
     * @return 删除结果
     */
    @DeleteMapping("{id}")
    public AjaxResult delete(@PathVariable String id) {
        List<String> split = StrUtil.split(id, ",");
        List<Ware> wares = wareService.listByIds(split);
        wareService.removeByIds(split);
        wares.stream().forEach(item -> {
            if ("2".compareTo(item.getLevel()) == 0) {
                LambdaUpdateWrapper<Ware> lqw = new LambdaUpdateWrapper<Ware>().eq(Ware::getParendId, item.getId());
                wareService.remove(lqw);
            }
            if ("1".compareTo(item.getLevel()) == 0) {
                LambdaUpdateWrapper<Ware> lqw = new LambdaUpdateWrapper<Ware>().eq(Ware::getParendId, item.getId());
                // 二城
                List<Integer> collect = wareService.list(lqw).stream().map(Ware::getId).distinct().collect(Collectors.toList());
                wareService.removeByIds(collect);
                // 三成
                LambdaUpdateWrapper<Ware> lqw1 = new LambdaUpdateWrapper<Ware>()
                        .in(Ware::getParendId, collect);
                wareService.remove(lqw1);
            }
        });
        return AjaxResult.success();
    }
}

